package ec.edu.ups.relevo.utils;

import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class JPAGenericDAO<T,ID> 
{
    protected Class<T>clasePersistente;
    @Inject
    protected EntityManager em;
    public JPAGenericDAO(Class<T> clasePersistente) 
    {
        this.clasePersistente = clasePersistente;
    }
    public void create(T entidad) 
    {
       try{
            em.persist(entidad);  
       }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
    public T read(ID id) 
    {
        T result=null;
       result=em.find(clasePersistente, id);  
        return result;
    }
    public void update(T entidad) 
    {
        try{
            em.merge(entidad);  
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }
    public void deleteById(ID id) 
    {
        this.delete(this.read(id));
    }
    public void delete(T entidad) 
    {
        try{
        	
        	em.remove(em.contains(entidad) ? entidad : em.merge(entidad));
  
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    
    }
    public List<T> listar()
    {
		String[] className= clasePersistente.getCanonicalName().split("\\.");
    	String query="select f from "+className[className.length-1]+"  f";
        Query q=em.createQuery(query);
        return q.getResultList();
    }
    public List<T> listarSinEliminados()
    {
		String[] className= clasePersistente.getCanonicalName().split("\\.");
    	String query="select f from "+className[className.length-1]+"  f where f.eliminado=false";
        Query q=em.createQuery(query);
        return q.getResultList();
    }

}
